<template>
  <div class="home-page">
    <!-- 统计数据区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <div class="stats-card">未开始订单：{{ statsData.unstarted }}</div>
      </el-col>
      <el-col :span="8">
        <div class="stats-card">行程中订单数：{{ statsData.ongoing }}</div>
      </el-col>
      <el-col :span="8">
        <div class="stats-card">已完成订单数：{{ statsData.completed }}</div>
      </el-col>
    </el-row>

    <!-- 图表区域：一行两个图表 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 折线图：客服咨询量 -->
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">客服每月接收咨询数量</div>
          <div ref="lineChartRef" class="chart-container"></div>
        </div>
      </el-col>

      <!-- 客户来源饼图 -->
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">客户来源分布</div>
          <div ref="pieChartRef" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <!-- 定制师占比饼图 -->
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">定制师完成订单占比</div>
          <div ref="pieCustomChartRef" class="chart-container"></div>
        </div>
      </el-col>

      <!-- 柱状图：近12个月订单量 -->
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-title">近12个月订单量统计</div>
          <div class="chart-scroll">
            <div ref="barChartRef" class="chart-container"></div>
          </div>

        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { getAllPageData } from '/@/api/page/page'
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { useMessage } from "/@/hooks/message";

// 注册ECharts组件
echarts.use([
  BarChart, LineChart, PieChart,
  GridComponent, TitleComponent, TooltipComponent, LegendComponent,
  CanvasRenderer
]);

// 图表容器引用
const lineChartRef = ref<HTMLDivElement | null>(null);
const pieChartRef = ref<HTMLDivElement | null>(null);
const pieCustomChartRef = ref<HTMLDivElement | null>(null);
const barChartRef = ref<HTMLDivElement | null>(null);

// 图表实例
let lineChart: echarts.ECharts | null = null;
let pieChart: echarts.ECharts | null = null;
let pieCustomChart: echarts.ECharts | null = null;
let barChart: echarts.ECharts | null = null;

// 统计数据（根据订单状态进行统计）
const statsData = ref({
  unstarted: 0,
  ongoing: 0,
  completed: 0
});


// 初始化图表实例
const initCharts = () => {
  if (lineChartRef.value) lineChart = echarts.init(lineChartRef.value);
  if (pieChartRef.value) pieChart = echarts.init(pieChartRef.value);
  if (pieCustomChartRef.value) pieCustomChart = echarts.init(pieCustomChartRef.value);
  if (barChartRef.value) barChart = echarts.init(barChartRef.value);
};

// 显示空数据提示配置
const getEmptyDataOption = (title: string) => ({
  title: {
    text: `暂无${title}数据`,
    left: 'center',
    top: 'middle',
    textStyle: { color: '#999', fontSize: 14 }
  },
  tooltip: { show: false },
  xAxis: { show: false },
  yAxis: { show: false },
  series: []
});

// 渲染图表（仅使用后端数据）
const renderCharts = (data: any) => {
  // 折线图：客服每月咨询量（依赖inquiriesList）
  const inquiryList = Array.isArray(data.inquiriesList) ? data.inquiriesList : [];
  const validInquiries = inquiryList.filter((item: any) => {
    const hasDate = item.month || item.date;
    const hasCount = item.count !== undefined || item.inquireId !== undefined;
    return item && hasDate && hasCount;
  });


  if (validInquiries.length > 0) {
    const months = validInquiries.map((item: any) => item.month || item.date);

    const counts = validInquiries.map((item: any) => item.count !== undefined ? item.count : item.inquireId);
    lineChart?.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: months, axisLabel: { rotate: 45 } },
      yAxis: { type: 'value', min: 0 }, // 咨询量不能为负数
      series: [{
        name: '咨询数量',
        type: 'line',
        data: counts
      }]
    });
  } else {
    lineChart?.setOption(getEmptyDataOption('客服咨询'));
  }

  // 客户来源饼图（依赖customerList）
  const customerList = Array.isArray(data.customerList) ? data.customerList : [];
  const validCustomers = customerList.filter((item: any) =>
      item && typeof item.cusSource === 'string' && item.cusSource.trim() !== '' &&
      typeof item.count === 'number' && item.count > 0
  );
  // 定义客户来源字典
  const customerSourceDict = {
    0: '飞猪',
    1: '58同城',
    2: '其他'
  };
  if (validCustomers.length > 0) {
    const sourceData = validCustomers.map((item: any) => ({
      name: customerSourceDict[item.cusSource] ,
      value: item.count
    }));
    pieChart?.setOption({
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { bottom: 10, type: 'scroll' },
      series: [{
        name: '来源分布',
        type: 'pie',
        radius: ['40%', '70%'],
        data: sourceData,
        emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } }
      }]
    });
  } else {
    pieChart?.setOption(getEmptyDataOption('客户来源'));
  }

  // 定制师完成订单饼图（依赖completedDesignedList）
  const designerList = Array.isArray(data.completedDesignedList) ? data.completedDesignedList : [];
  const validDesigners = designerList.filter((item: any) =>
      item && (typeof item.tailotrId === 'number' || typeof item.tailotrId === 'string') &&
      typeof item.count === 'number' && item.count > 0
  );
  if (validDesigners.length > 0) {
    const designerData = validDesigners.map((item: any) => ({
      name: `定制师${item.tailotrId}`,
      value: item.count
    }));
    pieCustomChart?.setOption({
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { bottom: 10, type: 'scroll' },
      series: [{
        name: '定制师占比',
        type: 'pie',
        radius: ['40%', '70%'],
        data: designerData,
        emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } }
      }]
    });
  } else {
    pieCustomChart?.setOption(getEmptyDataOption('定制师订单'));
  }

  // 近12个月订单柱状图（依赖orderNumbersList）
  const orderList = Array.isArray(data.orderNumbersList) ? data.orderNumbersList : [];
  const validOrders = orderList.filter((item: any) =>
      item && typeof item.createTime === 'string' && item.createTime.trim() !== '' &&
      typeof item.orderCount === 'number' && item.orderCount >= 0
  );
  if (validOrders.length > 0) {
    const months = validOrders.map((item: any) => {
      // 格式化日期（后端返回格式：YYYY-MM-DD HH:mm:ss）
      const dateStr = item.createTime.split(' ')[0]; // 提取日期部分
      return dateStr.replace(/-/g, '月').replace('月', '年', 1) + '月'; // 转为YYYY年MM月
    });
    const counts = validOrders.map((item: any) => item.orderCount);
    barChart?.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: months, axisLabel: { rotate: 45 } },
      yAxis: { type: 'value', min: 0 }, // 订单量不能为负数
      series: [{
        name: '订单量',
        type: 'bar',
        data: counts,
        itemStyle: { color: '#67C23A' }
      }]
    });
  } else {
    barChart?.setOption(getEmptyDataOption('月度订单'));
  }
};

onMounted(async () => {
  await nextTick();
  initCharts(); // 初始化图表实例
  try {
    const res = await getAllPageData();
    const data = res.data || {};

    // 处理订单状态统计（完全依赖后端orderStatusList）
    const orderStatusList = Array.isArray(data.orderStatusList) ? data.orderStatusList : [];
    statsData.value = {
      unstarted: orderStatusList.find((item: any) =>
          item?.orStatus === '0' && typeof item.count === 'number'
      )?.count || 0,
      ongoing: orderStatusList.find((item: any) =>
          item?.orStatus === '1' && typeof item.count === 'number'
      )?.count || 0,
      completed: orderStatusList.find((item: any) =>
          item?.orStatus === '2' && typeof item.count === 'number'
      )?.count || 0
    };

    // 渲染所有图表（仅使用后端数据）
    renderCharts(data);
  } catch (error) {
    useMessage().error('获取数据失败，请稍后重试');
    // 错误状态下显示空数据提示
    lineChart?.setOption(getEmptyDataOption('客服咨询'));
    pieChart?.setOption(getEmptyDataOption('客户来源'));
    pieCustomChart?.setOption(getEmptyDataOption('定制师订单'));
    barChart?.setOption(getEmptyDataOption('月度订单'));
  }

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

// 窗口 resize 时重绘图表
const handleResize = () => {
  lineChart?.resize();
  pieChart?.resize();
  pieCustomChart?.resize();
  barChart?.resize();
};

// 组件卸载时清理资源
onBeforeUnmount(() => {
  lineChart?.dispose();
  pieChart?.dispose();
  pieCustomChart?.dispose();
  barChart?.dispose();
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.home-page {
  padding: 20px;
  background-color: #f5f7fa;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  text-align: center;
  font-size: 16px;
  transition: transform 0.2s;
}
.stats-card:hover {
  transform: translateY(-2px);
}

.charts-row {
  margin-bottom: 30px;
}
.el-row .el-col {
  margin-bottom: 20px; /* 增加列间距 */
}
.chart-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
  padding-left: 4px;
  border-left: 3px solid #409EFF;
}

.chart-container {
  width: 100%;
  height: 400px;
}

@media (max-width: 768px) {
  .chart-container {
    height: 350px;
  }
  .chart-title {
    font-size: 14px;
  }
}
</style>
